package com.sinoflag.encode;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CustomPasswordEncoder implements PasswordEncoder {


    /**
     * 对输入的密码加密过程
     */
    @Override
    public String encode(CharSequence inputPwd) {
//        return DigestUtil.encrypt(inputPwd.toString());

        String data = inputPwd.toString();
        // 先做一次MD5加密
        data = DigestUtils.md5DigestAsHex(data.getBytes(StandardCharsets.UTF_8));
        // 再做一次SHA1加密
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            data = encodeHex(md.digest(data.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
        }


        return data;
    }


    /**
     * 密码校验过程
     */
    @Override
    public boolean matches(CharSequence inputPwd, String dbPwd) {
        // 判断密码是否存在
        if (inputPwd == null) {
            return false;
        }
        System.out.println("inputPwd==" + inputPwd + "  " + "dbPwd==" + dbPwd);
        if(dbPwd.contentEquals(this.encode(inputPwd))){
            return true;
        }
        return false;
    }

    private static final char[] HEX_CODE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * encode Hex
     *
     * @param bytes Data to Hex
     * @return bytes as a hex string
     */
    public static String encodeHex(byte[] bytes) {
        StringBuilder r = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            r.append(HEX_CODE[(b >> 4) & 0xF]);
            r.append(HEX_CODE[(b & 0xF)]);
        }
        return r.toString();
    }
}